/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.ss.config.configrations;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.zfes.snowy.base.datasource.DynamicDataSource;
@Configuration
@EnableTransactionManagement(order=2)
public class MybatisConfiguration  implements TransactionManagementConfigurer{
	
	 @Autowired
	 private DynamicDataSource dataSource;
	 
//	 @Autowired
//	 private DataSource dataSource;
	 
	 @Autowired
	 private MybatisProperties mybatisProperties;
	 
	@Bean(name = "sqlSessionFactory")
	@ConditionalOnMissingBean
	public SqlSessionFactory sqlSessionFactoryBean() throws Exception  {
	      SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
	       sessionFactoryBean.setDataSource(dataSource);
	       sessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
//	       sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
	       sessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource(mybatisProperties.getConfigLocation()));
		   return sessionFactoryBean.getObject();
	}
	@Bean
	@ConditionalOnMissingBean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
	   return new SqlSessionTemplate(sqlSessionFactory);
	}
	

	@Bean(name = "transactionManager")
	//@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}
}
